# encoding: UTF-8
import threading
import binascii
import socket
import string
import netaddr
import struct
import os
import serial
import commands
from getip import *

def get_default_gateway_linux():
    (status,output)=commands.getstatusoutput('route -n | head -n 3| tail -n 1 |awk \'{print $2}\'')
    return output
# SLIP decoder
class slip():
  def __init__(self):
    self.started = False
    self.escaped = False
    self.stream = ''
    self.packet = ''
    self.SLIP_END = '\xc0'    # dec: 192
    self.SLIP_ESC = '\xdb'    # dec: 219
    self.SLIP_ESC_END = '\xdc'  # dec: 220
    self.SLIP_ESC_ESC = '\xdd'  # dec: 221
    self.serialComm = None

  def append(self, chunk):
    self.stream += chunk.decode('iso-8859-1')

  def decode(self):
    packetlist = []
    for char in self.stream:
      # SLIP_END
      if char == self.SLIP_END:
        if self.started:
          packetlist.append(self.packet)
        else:
          self.started = True
        self.packet = ''
      # SLIP_ESC
      elif char == self.SLIP_ESC:
        self.escaped = True
      # SLIP_ESC_END
      elif char == self.SLIP_ESC_END:
        if self.escaped:
          self.packet += self.SLIP_END
          self.escaped = False
        else:
          self.packet += char
      # SLIP_ESC_ESC
      elif char == self.SLIP_ESC_ESC:
        if self.escaped:
          self.packet += self.SLIP_ESC
          self.escaped = False
        else:
          self.packet += char
      # all others
      else:
        if self.escaped:
          raise Exception('SLIP Protocol Error')
          self.packet = ''
          self.escaped = False
        else:
          self.packet += char
          self.started = True
    self.stream = ''
    self.started = False
    return (packetlist)
    
  def encode(self, packet):
    # Encode an initial END character to flush out any data that 
    # may have accumulated in the receiver due to line noise
    encoded = self.SLIP_END
    for char in packet:
      # SLIP_END
      if char == self.SLIP_END:
        encoded +=  self.SLIP_ESC + self.SLIP_ESC_END
      # SLIP_ESC
      elif char == self.SLIP_ESC:
        encoded += self.SLIP_ESC + self.SLIP_ESC_ESC
      # the rest can simply be appended
      else:
        encoded += char
    encoded += self.SLIP_END
    return (encoded)
#C0 00 19 90 00 01 00 DB DC A8 00 01 FF FF FF 00 DB DC A8 00 02 12 34 56 78 AB CD FF C0 
def appendedCheckSum(ipset):
    sum=0
    for char in ipset:
        sum += ord(char)
    sum=sum&255      
    return ipset + chr(sum)

def checkSum(ipset):
    sum=0
    for char in ipset[:-1]:
        sum=sum + ord(char)
    sum=sum&255
    if sum != ord(ipset[-1]):
        print sum
        print ord(ipset[-1])
        return False
    return True
def analysisfunc(recvstr,p,ser1,ser2):
  ##c000149000090002dbdca80b64ffff0000dbdca80101eec0 slip encode
  ## 00149000090002C0A80B64FFFF0000C0A80101EE slip decode
  try:
      ACK=binascii.a2b_hex("C00007009000AB42C0")
      NAK=binascii.a2b_hex("C00008009000AC01D6C0")
      NAKCanshu = binascii.a2b_hex("C0000a009000AC09000352C0")
      slipModel=slip()
      slipModel.stream = recvstr
      a=slipModel.decode()
      ipset=a[0]
      if checkSum(ipset) == False:
          print "naK"
          return NAK 
      if ipset.find('\x09\x00\x02') == 4:
          print "set ip"
          shellSetIp = "ifconfig eth0 "+str(ord(ipset[7]))+'.'+str(ord(ipset[8]))+'.'+str(ord(ipset[9]))+'.'+str(ord(ipset[10]))+" netmask "+str(ord(ipset[11]))+'.'+str(ord(ipset[12]))+'.'+str(ord(ipset[13]))+'.'+str(ord(ipset[14]))
          print shellSetIp
          shellSetGw = "route add default gw "+str(ord(ipset[15]))+'.'+str(ord(ipset[16]))+'.'+str(ord(ipset[17]))+'.'+str(ord(ipset[18]))
          print shellSetGw
          f = open('/root/saveip','r')
          ipInfo = f.readlines()
          f.close()
          print ipInfo
          ipInfo[0] = ipInfo[0][:-1]
          ipInfo[1] = ipInfo[1][:-1]
          (status1,output)=commands.getstatusoutput(shellSetIp)
          (status2,output)=commands.getstatusoutput(shellSetGw)
          if status1 == 0:
              ipInfo[0] = shellSetIp
          if status2 == 0:
              ipInfo[1] = shellSetGw
          f = open('/root/saveip','w')
          f.write(ipInfo[0]+'\n')
          f.write(ipInfo[1]+'\n')
          print 'ipInfo[0]='+ ipInfo[0]
          print 'ipInfo[1]='+ ipInfo[1]
          f.close()
          os.system('sync')
          if status1!=0 or status2 !=0:
              return NAKCanshu
          return ACK
      elif ipset.find('\x09\x00\x01')==4:
          #print "localip:"+socket.gethostbyname(socket.gethostname())
          #ipAddress = socket.gethostbyname(socket.gethostname()) 
          ipAddress = get_ip_address('eth0')
          print ipAddress
          ip = netaddr.IPNetwork(ipAddress)
          ipAddress = ipAddress.split('.')
          # print ip
          ipnetmask = get_Mask()
          ipnetMask = str(ipnetmask).split('.')
          print ipnetMask
          ipgateWay = get_default_gateway_linux().split('.')
          print ipgateWay
         # ipgateWay = '192.168.1.1' 
         # ipgateWay = ipgateWay.split('.')
          resultCode = binascii.a2b_hex('00140090090003')+chr(int(ipAddress[0]))+chr(int(ipAddress[1]))+chr(int(ipAddress[2]))+chr(int(ipAddress[3]))+chr(int(ipnetMask[0]))+chr(int(ipnetMask[1]))+chr(int(ipnetMask[2]))+chr(int(ipnetMask[3]))+chr(int(ipgateWay[0]))+chr(int(ipgateWay[1]))+chr(int(ipgateWay[2]))+chr(int(ipgateWay[3]))
          resultCode = appendedCheckSum(resultCode)       
          resultCode = slipModel.encode(resultCode)
          return resultCode
      elif ipset.find('\x09\x04\x01')==4:
          count = len(open('/root/saveip','r').readlines())
          if count==1:
              resultCode = binascii.a2b_hex('0009009009040302')
              resultCode = appendedCheckSum(resultCode)
              resultCode = slipModel.encode(resultCode)
              return resultCode
          else:
              resultCode = binascii.a2b_hex('0009009009040301')
              resultCode = appendedCheckSum(resultCode)
              resultCode = slipModel.encode(resultCode)
              return resultCode
      elif ipset.find('\x09\x01\x01')==4:
          baudrate = os.popen('cat /root/savebaudrate').read()
          baudrate = int(baudrate)
          ser1 = serial.Serial('/dev/ttyO1', baudrate, timeout=1)
          ser2 = serial.Serial('/dev/ttyO2',baudrate,timeout=1)
          if  baudrate==38400:
              resultCode = binascii.a2b_hex('0009009009010302')
              resultCode = appendedCheckSum(resultCode)
              resultCode = slipModel.encode(resultCode)
              return resultCode
          elif baudrate==9600:
              resultCode = binascii.a2b_hex('0009009009010301')
              resultCode = appendedCheckSum(resultCode)
              resultCode = slipModel.encode(resultCode)
              return resultCode
      elif ipset.find('\x09\x01\x02')==4:
          baudrate = os.popen('cat /root/savebaudrate').read()
          baudrate = int(baudrate)
          if ipset.find('\x09\x01\x02\x01')==4:
              os.system('echo 9600 > /root/savebaudrate')
              os.system('sync')
              ser1.baudrate = 9600
              ser2.baudrate = 9600
          elif ipset.find('\x09\x01\x02\x02')==4:
              os.system('echo 38400 > /root/savebaudrate')
              os.system('sync')
              ser1.baudrate = 38400
              ser2.baudrate = 38400
          return ACK
      elif ipset.find('\x09\x05\x01')==4:
          sipserver = os.popen('cat /root/sipserver').read()
          sipserver = sipserver.split('.')
          resultCode = binascii.a2b_hex('000c0090090503') + chr(int(sipserver[0])) + chr(int(sipserver[1]))  + chr(int(sipserver[2]))+ chr(int(sipserver[3]))
          resultCode = appendedCheckSum(resultCode)
          resultCode = slipModel.encode(resultCode)
          return resultCode
      elif ipset.find('\x09\x05\x02')==4:
          setSipServer = str(ord(ipset[7]))+'.'+str(ord(ipset[8]))+'.'+str(ord(ipset[9]))+'.'+str(ord(ipset[10]))
          accountInfo = os.popen('cat /root/accountInfo').readlines()
          accountName = accountInfo[0]
          accountPwd = accountInfo[1]
          setCommand = 'register sip:'+accountName+'@'+setSipServer+' '+setSipServer+' '+accountPwd+'\n'
          p.stdin.write('ungister')
          p.stdin.write(setCommand)
          os.system('echo '+setSipServer+'> /root/sipserver');
          os.system('sync')
          return ACK
      elif ipset.find('\x09\x06\x01')==4:
          accountInfo = os.popen('cat /root/accountInfo')
          accountName = accountInfo[0]
          accountPwd = accountInfo[1]
          lenName = len(accountName)
          lenPwd = len(accountPwd)
          totalLen = lenName + lenPwd + 10
          canshuStr = binascii.a2b_hex('03') + chr(int(lenName))
          for i in range(len(lenName)):
              canshuStr += chr(int(lenName[i]))
          canshuStr += chr(int(lenPwd))
          for i in range(len(lenPwd)):
              canshuStr += chr(int(lenPwd))
          totalStr = binascii.a2b_hex('00')+chr(totalLen) + binascii.a2b_hex('00900906') + canshuStr
          resultCode = appendedCheckSum(totalStr)
          resultCode = slipModel.encode(resultCode)
          return resultCode
      elif ipset.find('\x09\x06\x02') == 4:
          lenName = int(str(ord(ipset[7])))
          lenPwd = int(str(ord(ipset[8+lenName])))
          bName = ipset[8:lenName]
          bPwd = ipset[9+lenName:lenPwd]
          strName
          strPwd
          for i in range(lenName):
              strName += str(ord(bName[i]))
          for i in range(lenPwd):
              strPwd += str(ord(bPwd[i]))
          sipserver = os.popen('cat /root/sipserver').read()
          setCommand = 'register sip:'+strName+'@'+sipserver+' '+sipserver+' '+accountPwd+'\n'
          p.stdin.write('ungister')
          p.stdin.write(setCommand)
          os.system('echo '+strName+'> /root/accountInfo');
          os.system('echo '+strPwd +'>> /root/accountInfo')
          os.system('sync')
          return ACK
      elif ipset.find('\x09\x06\x03') == 4:
          return ACK   
  except Exception,ex:
      print Exception,":",ex
      return NAKCanshu
      
analysisfunc(binascii.a2b_hex("C000110090090602040700000203040506d1C0"))
